package com.health.common.utils;

import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class MinIOUtils {

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucket-name}")
    private String defaultBucket;
    @Value("${minio.endpoint}")
    String url;
    /**
     * 检查存储桶是否存在
     */
    public boolean bucketExists(String bucketName) throws Exception {
        return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
    }

    /**
     * 创建存储桶
     */
    public void createBucket(String bucketName) throws Exception {
        if (!bucketExists(bucketName)) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
    }

    /**
     * 上传文件（默认存储桶）
     * @param file 上传的文件
     * @return 文件上传后的完整URL
     */
    public String uploadFile(MultipartFile file) throws Exception {
        if (file == null || file.isEmpty()) {
            throw new RuntimeException("上传文件不能为空");
        }
        String originalFilename = file.getOriginalFilename();
        String suffix;
        if (originalFilename == null || originalFilename.lastIndexOf(".") == -1) {
            suffix="";
        }
        else suffix= originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
        String newFileName = UUID.randomUUID().toString();
        newFileName = newFileName.substring(0, 8)+"."+suffix;
        uploadFile(defaultBucket, file, newFileName);
        //返回完整url
        return url + "/" + defaultBucket + "/" + newFileName;
    }

    /**
     * 上传文件（指定存储桶）
     */
    public void uploadFile(String bucketName, MultipartFile file, String objectName) throws Exception {
        // 检查桶是否存在，不存在则创建
        createBucket(bucketName);
        // 上传文件
        try (InputStream inputStream = file.getInputStream()) {
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(objectName)
                            .stream(inputStream, file.getSize(), -1)  // -1表示自动检测文件大小
                            .contentType(file.getContentType())  // 设置文件MIME类型
                            .build()
            );
        }
    }

    /**
     * 下载文件（获取文件输入流）
     */
    public InputStream downloadFile(String objectName) throws Exception {
        return downloadFile(defaultBucket, objectName);
    }

    public InputStream downloadFile(String bucketName, String objectName) throws Exception {
        return minioClient.getObject(
                GetObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .build()
        );
    }

    /**
     * 删除文件
     */
    public void deleteFile(String objectName) throws Exception {
        String[] split = objectName.split("/");
        objectName = split[split.length - 1];
        deleteFile(defaultBucket, objectName);
    }

    public void deleteFile(String bucketName, String objectName) throws Exception {
        minioClient.removeObject(
                RemoveObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .build()
        );
    }

    /**
     * 获取文件临时访问URL（默认7天有效期）
     */
    public String getPresignedUrl(String objectName) throws Exception {
        return getPresignedUrl(defaultBucket, objectName, 7, TimeUnit.DAYS);
    }

    public String getPresignedUrl(String bucketName, String objectName, int duration, TimeUnit unit) throws Exception {
        return minioClient.getPresignedObjectUrl(
                GetPresignedObjectUrlArgs.builder()
                        .method(Method.GET)
                        .bucket(bucketName)
                        .object(objectName)
                        .expiry(duration, unit)  // 有效期
                        .build()
        );
    }

    /**
     * 获取所有存储桶
     */
    public List<Bucket> listBuckets() throws Exception {
        return minioClient.listBuckets();
    }
}